cap log close
clear all
set more off
set matsize 11000
set maxvar 120000

sysdir set PLUS "S:\Project\DemoSos2\common\felles\JR_RG\DrVA\plus"

*Main data pathway globals, set directory to clean data folder
global results "S:\Project\DemoSos2\common\felles\JR_RG\DrVA\ResultsRev2\"
global cleandata "S:\Project\DemoSos2\common\felles\JR_RG\DrVA\CleanData\"

cd "$cleandata"

*---------------------------------------------------------*
* Reasons for swap (raw data): Table A1
*---------------------------------------------------------*
log using "$results/motivestoswap.log", replace
use "S:\Project\DemoSos2\data2020\KUHR\PasientLister.dta" 
tab  opprettelseaarsak
log close
								  
*---------------------------------------------------------*
* Do patients anticipate GP list reduction/termination****
*---------------------------------------------------------*
*Start with raw files
use lopenr gpid year red_term_swap o_swap using "patient_gp2.dta", clear
sort lopenr year
*encode lopenr, gen(lopenr_number)
replace red_term_swap=0 if red_term_swap==.
replace o_swap=0 if o_swap==.
gen exog_swap_next_year = red_term_swap[_n+1] if lopenr==lopenr[_n+1]
eststo clear
eststo: reg o_swap exog_swap_next_year, robust
estadd ysumm
esttab using "$results/AnticipateExogSwap.txt", ///
	replace label b(4) se(4) r2 star(* 0.1 ** 0.05 *** 0.01) ///
	stats(ymean N, fmt(%10.3g))

*---------------------------------------------------------*
* GP per municipality
*---------------------------------------------------------*
use "gp_charateristics.dta", clear
keep gpid kommunenr year
duplicates drop
ge d = 1 
collapse (sum) d, by(kommunenr year)
keep if year==2010
*truncate distribution to be easier to read graph
replace d = 100 if d > 100 & d!=.
su d, d
local p25 = r(p25)
local p75 = r(p75)
histogram d, discrete frequency xlabel(0 `p25' `p75' 20 40 60 80 100)  graphregion(color(white))  xtitle(Number of Doctors) 
graph export "$results/fig_a2.pdf", as(pdf) replace


*---------------------------------------------------------*
*FE analysis*
*---------------------------------------------------------*
use  clean_patientlevel_file_rev3.dta, clear
keep if yr_str_exog_swap >= 2005 & yr_str_exog_swap<=2014
keep if str_exogGPIDnew!=. 


* largest mobility group 
a2group, individual(str_exogGPIDnew) unit(str_exogGPIDprev) groupvar(pair)
bys pair: ge size_pair = _N
tab pair
drop if size_pair < 10 ///largest mobility group has 99%

merge 1:1 str_exogGPIDnew lopenr  using "$results/fe_addon_lo2.dta"
drop _merge

preserve
* from how many municip come my patients?
keep if str_exog_age>=55
keep str_exogGPIDprev str_exog_muni
duplicates drop
bys str_exogGPIDprev: ge n =_N
su n
restore


ge death5 = mortality_5year
ge death2 = mortality_2year
for num 25 35 45 55: ge death5_X = mortality_5year if str_exog_age>=X
for num 25 35 45 55: ge death2_X = mortality_2year if str_exog_age>=X
for var heart cancer ext resp mental accident suicide homicide: ge X2y_55 = X_2y if str_exog_age>=55
for var npr2 npr_noer2 npr_in2 npr_out2 charlindex2 sl_days2: ge X55 = X if str_exog_age>=55

* doc characteristics
ge dr_long_list = dr_list_length_str_exog_swap > 1100 if dr_list_length_str_exog_swap!=.
ge dr_old = dr_age_str_exog_swap >=40 if dr_age_str_exog_swap!=.
ge dr_max_list =  dr_max_str_exog_swap> 1200 if  dr_max_str_exog_swap!=.
ge dr_capacity = dr_max_str_exog_swap-dr_list_length_str_exog_swap >=0

rename dr_age_str_exog_swap 		age_doc
rename dr_spec_str_exog_swap 		sp_doc
rename dr_list_length_str_exog_swap list_doc
rename dr_male_str_exog_swap  		male_doc
rename dr_share_str_exog_swap		share_doc
rename dr_group_str_exog_swap 		group_doc
rename dr_max_str_exog_swap 		maxlist_doc

* 1 - observables
local predictors "dr_old dr_long_list dr_max_list dr_spec_str_exog_swap dr_list_length_str_exog_swap dr_male_str_exog_swap dr_share_str_exog_swap dr_group_str_exog_swap dr_max_str_exog_swap dr_capacity"	

lab var str_exog_age 	"Age at swap"
lab var male 			"Male"
lab var NORborn			"Born in Norway"
lab var edu_yrs 		"Years of Eduaction"
lab var married 		"Married"
lab var lab_income5 	"Labor income"
lab var tot_income5 	"Total Income"
lab var unempben5		"Received Unemploment Benefits?"
lab var innav5  			"Any welfare benefit"	
lab var	mortality_2year 	"Mortality 2 years after"
lab var mortality_5year 	"Mortality 5 years after"

label var death2_55 	"2-years mortality for 55+"
label var bweight_2y 	"Birthweight"
label var heart2y_55 	"Mortality: heart conditions"
label var cancer2y_55 	"Mortality: cancer"
label var ext2y_55 		"Mortality: external conditions"
label var resp2y_55 	"Mortality: respiratory conditions"
label var mental2y_55 	"Mortality: mental health conditions"
label var accident2y_55	"Mortality: accident conditions"
label var sl_days255 	"Nb sick leave days"
label var npr255 		"Nb of hospitalizations"
label var npr_noer255 	"Nb of hospitalizations - not ER"
label var charlindex255 "Charlson Index"

bys str_exogGPIDnew: ge n = _n
* recode main VA measure (more VA - better doc, less mortality) 
ge newva = -afe_death2_55
local va "newva" 
su `va', d
gen stdva = (`va'-r(mean))/r(sd)
local va "stdva"
lab var stdva "Standardized VA"

keep if str_exogGPIDnew!=. & stdva!=. & str_exog_age>= 55

replace total_days_sl_base = 0 if total_days_sl_base ==. & lab_income!=.

* -----------------------------------------------------------------------------
* table A1
* number of patients involved in swap
* -----------------------------------------------------------------------------
preserve
keep lopenr str_exogGPIDprev str_exogGPIDnew

*Patients per new GP in a swap
bys str_exogGPIDprev str_exogGPIDnew: ge tag = _n
replace tag=. if tag!=1 
bys str_exogGPIDprev str_exogGPIDnew: ge PatientsPerSwap = _N
replace PatientsPerSwap=. if tag!=1
sum PatientsPerSwap
*Number of new GPs per old GP
bysort str_exogGPIDprev: egen NewGPPerPrevGP = sum(tag)
bys str_exogGPIDprev: ge tag2 = _n
replace NewGPPerPrevGP=. if tag2!=1
sum NewGPPerPrevGP	
*Number of patients per old gep
bys str_exogGPIDprev: ge PatientsPerPrevGP = _N
replace PatientsPerPrevGP=. if tag2!=1
sum PatientsPerPrevGP	

log using "$results/tablea2", text replace
sum PatientsPerSwap NewGPPerPrevGP PatientsPerPrevGP	
log close

restore


su age_doc if n == 1, d
ge dage_doc = 1 if age_doc<= 30
replace dage_doc = 2 if age_doc >30 & age_doc <= 40
replace dage_doc = 3 if age_doc >40 & age_doc <= 50
replace dage_doc = 4 if age_doc >50 & age_doc <= 60
replace dage_doc = 5 if age_doc >60 & age_doc !=.
tab dage_doc, ge(dage_doc_)

ge age_doc2 = age_doc^2
ge list_doc2 = list_doc^2
ge maxlist_doc2=maxlist_doc^2


* rescale income
replace tot_income = tot_income/1000

local baseline 	"college0 married_base NORborn antbarn tot_income hours dwoverfor  total_base reimburse_base total_days_sl_base any_chronic0 nb_chronic0"
local baseline2 "college0 married_base NORborn antbarn tot_income hours dwoverfor  total_base reimburse_base total_days_sl_base any_chronic0 nb_chronic0 dnpr_base npr_base charlindex_base"
global controls "i.yr_str_exog_swap i.str_exog_age male" 

* to use hours for everyone, replace hours = 0 if no income
replace hours = 0 if lab_income!=. & hours==.

* number of chronic conditions at baseline
egen nb_chronic0 = rsum(cancer_base digest_chronic_base heart_chronic_base endoc_chronic_base any_cardiogp_base) if yr_str_exog_swap>=2008 



* -----------------------------------------------------------------------------
* fallback condition (abaluck et al, p.1589)
* -----------------------------------------------------------------------------
reg death2_55 age_doc age_doc2 i.sp_doc i.male_doc i.share_doc list_doc list_doc2 maxlist_doc maxlist_doc2 i.group_doc $controls
predict uhat, res

eststo fallb1: areg uhat stdva $controls, a(str_exogGPIDprev) cl(str_exogGPIDnew) 

esttab fallb1 using "$results/fallback.tex", ///
	booktabs legend replace  label star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) b(4) se(4) 
eststo clear


* -----------------------------------------------------------------------------
* RA check
* -----------------------------------------------------------------------------
local age = 55 
*R1 - comment 2.1 (Table 1 joint test)
eststo all: areg stdva `baseline' $controls if str_exog_age>= `age',  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
testparm `baseline'
estadd scalar fstat = r(F)
estadd scalar pv = r(p)
eststo all

eststo all2: areg stdva `baseline2' $controls if str_exog_age>= `age',  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
testparm `baseline2'
estadd scalar fstat = r(F)
estadd scalar pv = r(p)
eststo all2

esttab  all all2 using "$results/ra_all.tex", ///
	booktabs legend replace    mtitles("Controls" "Controls-Hospital" )  ///
	label star(* 0.1 ** 0.05 *** 0.01) stats(emp fstat pv N, fmt(%9.3g)) b(4) se(4) 


* Table 1
foreach var in `baseline2' {
	eststo `var': areg `var' stdva  $controls if str_exog_age>= `age' & married_base!=. & hs0!=. & dnpr_base!=. & tot_income!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'

}
esttab college0 married_base NORborn antbarn tot_income hours dwoverfor  total_days_sl_base total_base reimburse_base any_chronic0 nb_chronic0 dnpr_base npr_base charlindex_base using "$results/table1.tex", ///
	legend replace keep(stdva)     ///
	label star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) b(3) se(3) ///
	mtitles("College Degree" "Married" "Born in Norway" "Nb of Children" "Total Income" "Hours" "Any Welfare Benefits" "Sick Leave" "Nn. GP Visits" "Reimbursements" "Any Chronic Conditions" "Nb Chronic Conditions" "Any Hospitalization" "Nb Hospitalizations"  "Charlson Index")	


foreach var in `baseline' {
	eststo `var': areg `var' stdva  $controls if str_exog_age>= `age' & married_base!=. & hs0!=. & tot_income!=. & total_base!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'

}
esttab college0 married_base NORborn antbarn tot_income hours dwoverfor  total_days_sl_base total_base reimburse_base any_chronic0 nb_chronic0 using "$results/table1.tex", ///
	legend append keep(stdva)     ///
	label star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) b(3) se(3) ///
	mtitles("College Degree" "Married" "Born in Norway" "Nb of Children" "Total Income" "Hours" "Any Welfare Benefits" "Sick Leave" "Nn. GP Visits" "Reimbursements" "Any Chronic Conditions" "Nb Chronic Conditions")	
est clear


* Appendix Table without controls for age or gender (Table A7)
foreach var in str_exog_age male `baseline2' {
	eststo `var': areg `var' stdva  i.yr_str_exog_swap if str_exog_age>= 55 & married_base!=. & hs0!=. & tot_income!=. & total_base!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'

}
esttab str_exog_age male college0 married_base NORborn antbarn using "$results/table_a7.tex", ///
	legend replace keep(stdva)     ///
	label star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) b(3) se(3) ///
	mtitles("Age" "Male" "College Degree" "Married" "Born in Norway" "Nb Children")	

esttab tot_income hours dwoverfor  total_days_sl_base total_base reimburse_base using "$results/table_a7.tex", ///
	legend append keep(stdva)     ///
	label star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) b(3) se(3) ///
	mtitles("Total Income" "Hours" "Any Welfare Benefits" "Sick Leave" "Nn. GP Visits" "Reimbursements")	

esttab any_chronic0 nb_chronic0 dnpr_base npr_base charlindex_base using "$results/table_a7.tex", ///
	legend append keep(stdva)     ///
	label star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) b(3) se(3) ///
	mtitles("Any Chronic Conditions" "Nb Chronic Conditions" "Any Hospitalization" "Nb Hospitalizations"  "Charlson Index")	

	
* Table A10
reg death2_55 age_doc age_doc2 i.sp_doc i.male_doc i.share_doc list_doc list_doc2 maxlist_doc maxlist_doc2 i.group_doc if str_exog_age>= `age' & married_base!=. & hs0!=. & tot_income!=.
predict dhat
label var dhat "Linear Prediction"

foreach var in  `baseline2' {
	eststo `var': areg `var' dhat $controls if str_exog_age>= `age' & married_base!=. & hs0!=. & tot_income!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
}

esttab college0 married_base NORborn antbarn tot_income hours dwoverfor  total_days_sl_base total_base reimburse_base any_chronic0 nb_chronic0 dnpr_base npr_base charlindex_base using "$results/ra_va55new.tex", ///
	legend replace keep(dhat)     ///
	label star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) b(3) se(3) ///
	mtitles("College Degree" "Married" "Born in Norway" "Nb of Children" "Total Income" "Hours" "Any Welfare Benefits" "Sick Leave" "Nn. GP Visits" "Reimbursements" "Any Chronic Conditions" "Nb Chronic Conditions" "Any Hospitalization" "Nb Hospitalizations"  "Charlson Index")	


* Figures A5 
local age = 55
*Run balance test with previous GP FE and controls, standardized, append
foreach var in  `baseline2' {
	areg `var' $controls if str_exog_age>= `age' & married_base!=. & hs0!=. & dnpr_base!=. & tot_income!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	predict res_`var', residuals
	reg res_`var' stdva if e(sample), cl(str_exogGPIDnew) 
	local coef = string(_b[stdva],"%9.3f")
	local se = string(_se[stdva],"%9.3f")
	
	preserve
	sort stdva
	xtile p20 = stdva, nq(20)
	collapse stdva res_`var', by(p20)
	twoway (scatter res_`var' stdva, mcolor(navy)) (lfit res_`var' stdva, lcolor(red)), graphregion(color(white)) bgcolor(white)  ///
		ytitle("Residual Change") xtitle("GP VA") note("Coefficient=`coef'" "(`se')", position(5) ring(0) size(medsmall)) legend(off)
	graph export "$results/res_`var'.pdf", as(pdf) replace
	restore
}


*Figure A4
areg death2_55 `baseline' $controls,  a(str_exogGPIDprev)
predict yhat, xb
areg yhat stdva, a(str_exogGPIDprev) cl(str_exogGPIDnew) 
local coef = string(_b[stdva],"%9.3f")
local se = string(_se[stdva],"%9.3f")

areg  death2_55  stdva $controls if str_exog_age>=55 & heart_2y!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
predict yhat_post, xb
local coef3 = string(_b[stdva],"%9.3f")
local se3 = string(_se[stdva],"%9.3f")

preserve
sort stdva
xtile p20 = stdva, nq(20)
collapse stdva yhat yhat_post, by(p20)
twoway (scatter yhat stdva, mcolor(navy)) (lfit yhat stdva, lcolor(red) lpattern(solid)) ///
	(lfit yhat_post stdva, lcolor(red) lpattern(dash)), graphregion(color(white)) bgcolor(white) title("`var'") ///
	ytitle("Predicted Mortality", size(medium)) xtitle("GP VA") note("Solid Coefficient=`coef'(S.E. `se'); Dashed Coefficient=`coef3'(S.E. `se3')", size(medsmall)) ///
	legend(off) ylabel(0(0.01)0.09)
graph export "$results/res_yhatpost.pdf", as(pdf) replace


restore
drop yhat*


* -----------------------------------------------------------------------------
* 3 - Effects: TABLE 2
* -----------------------------------------------------------------------------
eststo c1: areg  age_death stdva $controls if str_exog_age>=55,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
su age_death if e(sample)
estadd scalar mean = r(mean)
eststo c1

eststo c1_cont: areg  age_death stdva  $controls hs0 NORborn antbarn tot_income dwoverfor bigcity birthorder i.total_base if  str_exog_age>=55,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
eststo c1_contsame: areg  age_death stdva $controls if  str_exog_age>=55 & e(sample),  a(str_exogGPIDprev) cl(str_exogGPIDnew) 

ge rest_2y = mortality_2year== 1 & heart_2y == 0 &  resp2y_55 ==0 & cancer_c_2y == 0 if  str_exog_age>=55 & heart_2y!=.

foreach var in death2_55 heart_2y cancer_c_2y resp2y_55 rest_2y  {
	eststo `var': areg  `var' stdva $controls if str_exog_age>=55 & heart_2y!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
}
esttab c1 c1_cont c1_contsame using "$results/table2.tex", booktabs legend replace keep(stdva) ///
	mtitles("Age at Death") label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 
esttab death2_55 cancer_c_2y  heart_2y resp2y_55  rest_2y using "$results/table2.tex", booktabs legend append keep(stdva) ///
	mtitles("All Cause Mortality" "Malign Cancer ICD10 C" "Cardiovascular ICD10 I" "Respiratory ICD10 J" "Rest" ) label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 
est clear


** Table A15: split at median age of swap (62)
eststo c1: areg  age_death stdva $controls if str_exog_age>=62,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
su age_death if e(sample)
estadd scalar mean = r(mean)
eststo c1

foreach var in death2_55 heart_2y cancer_c_2y resp2y_55  rest_2y  {
	eststo `var': areg  `var' stdva $controls if str_exog_age>=62 & heart_2y!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
}
esttab c1 death2_55 cancer_c_2y heart_2y resp2y_55  rest_2y using "$results/lr_causesmed.tex", booktabs legend replace keep(stdva) ///
	mtitles("Age at Death" "All Cause Mortality" "Malign Cancer ICD10 C" "Cardiovascular ICD10 I" "Respiratory ICD10 J" "Rest" ) label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 
est clear

** FOR 55-61
eststo c1: areg  age_death stdva $controls if str_exog_age>=55 & str_exog_age<= 61,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
su age_death if e(sample)
estadd scalar mean = r(mean)
eststo c1

foreach var in death2_55 heart_2y cancer_c_2y resp2y_55  rest_2y  {
	eststo `var': areg  `var' stdva $controls if str_exog_age>=55 & str_exog_age<= 61 & heart_2y!=.,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
}
esttab c1 death2_55 cancer_c_2y heart_2y resp2y_55  rest_2y using "$results/lr_causesmed.tex", booktabs legend append keep(stdva) ///
	mtitles("Age at Death" "All Cause Mortality" "Malign Cancer ICD10 C" "Cardiovascular ICD10 I" "Respiratory ICD10 J" "Rest" ) label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 
est clear





* -----------------------------------------------------------------------------
* 3 - Effects: TABLES 4, 5, 6, 7 
* -----------------------------------------------------------------------------
* categories for PC variables
su reimburse_def1, d
gen lreimb1 = ln(reimburse_def1+1)
su reimburse_def1, d 
ge dhigh_reimb1 = reimburse_def1 >= r(p50) if reimburse_def1!=.
su total1, d
ge hightotal1 = total1>=r(p50) if total1!=.

local k = 1
ge gp_other`k' = total`k' - cancer`k' 
ge dgp_other`k' = gp_other`k'>0 if gp_other`k'!=.


* Table 4, 6: post swap use of gp change?
foreach k in 1 {
	local j = `k'-1
	
	foreach var in total`k' procedure`k'  labtest`k' sl`k' reimburse_def`k'  high_reimb`k'  cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k'  {
		eststo d`var': areg d`var' stdva $controls if  str_exog_age>=55 ,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
		su d`var' if e(sample)
		estadd scalar mean = r(mean)
		eststo d`var'
	}
	
	foreach var in total`k' hightotal`k' procedure`k' labtest`k' sl`k' lreimb`k' reimburse_def`k' cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k'   {
		eststo `var': areg `var' stdva $controls if  str_exog_age>=55 ,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
		su `var' if e(sample)
		estadd scalar mean = r(mean)
		eststo `var'
		}
	
		
	esttab dtotal1 dprocedure1 dlabtest1 dsl1 dreimburse_def1 dhigh_reimb1  using "$results/table4.tex",  booktabs legend replace ///
	label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) keep(stdva) ///
	mtitles("Consultations" "Procedure" "Lab Test"  "Sick Leave-all" "Reimbursement" "Reimb>Median") 
	
	esttab  total1 procedure1  labtest1 sl1 lreimb1 hightotal`k'  using "$results/table4.tex",  booktabs legend append ///
	label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) keep(stdva) ///
	mtitles("Consultations" "Procedure" "Lab Test" "Sick Leave-all" "Log Reimbursement") 
	
	esttab  dcancer`k' ddiag_L`k' ddiag_D`k' ddiag_K`k' dgp_other`k'  using "$results/table6.tex",  booktabs legend replace ///
	label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) keep(stdva) ///
	mtitles( cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k' ) 
	
	esttab   cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k'   using "$results/table6.tex",  booktabs legend append ///
	label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) keep(stdva) ///
	mtitles( cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k' ) 

}

local k= 1
foreach k in 1 {
	local j = `k'-1
	
	foreach var in cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k'  {
		eststo d`var': areg d`var' stdva $controls if  str_exog_age>=55 & dtotal1==1 ,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
		su d`var' if e(sample)
		estadd scalar mean = r(mean)
		eststo d`var'
	
		eststo `var': areg `var' stdva $controls if  str_exog_age>=55 & dtotal1==1 ,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
		su `var' if e(sample)
		estadd scalar mean = r(mean)
		eststo `var'
	}
	
		
	esttab  dcancer`k' ddiag_L`k' ddiag_D`k' ddiag_K`k' dgp_other`k'  using "$results/lr_va`k'_diagv2.tex",  booktabs legend replace ///
	label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) keep(stdva) ///
	mtitles( cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k' ) 
	
	esttab   cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k'   using "$results/lr_va`k'_diagv2.tex",  booktabs legend append ///
	label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) keep(stdva) ///
	mtitles( cancer`k' diag_L`k' diag_D`k' diag_K`k' gp_other`k' ) 

}


* Table 5
drop *npr*rest*
for num 1: egen npr_cancerX = rsum(npr_cancer_dX npr_cancer_cX) if npr_cancer_dX!= . |  npr_cancer_cX!=.
for num 1: egen dnpr_cancerX = rmax(dnpr_cancer_dX dnpr_cancer_cX) if dnpr_cancer_dX!= . |  dnpr_cancer_cX!=.

ge npr_rest1 = npr1-npr_cancer1 if yr_str_exog_swap>=2007 & dnpr1==1
ge dnpr_rest1 = npr1==1 & npr_cancer1==0 if yr_str_exog_swap>=2007 & dnpr1==1

foreach var in npr1 npr_er1 npr_noer1 npr_in1 npr_out1 npr_cancer1 npr_cancer_c1 npr_rest1 ///
					dnpr_er1 dnpr_noer1 dnpr_in1 dnpr_out1 dnpr_cancer1 dnpr_cancer_c1 dnpr_rest1   {
		replace `var' = . if dnpr1==0
	}

foreach k in 1 {
	local j = `k'-1
	
	* post swap hospitalizations: k years later
	foreach var in npr npr_er npr_noer npr_in npr_out npr_cancer npr_cancer_c npr_rest {
		eststo r`var': areg d`var'`k' stdva $controls if str_exog_age>=55,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
		su d`var'`k' if e(sample)
		estadd scalar mean = r(mean)
		eststo r`var'
		
		eststo `var': areg `var'`k' stdva $controls if str_exog_age>=55 & dnpr`k'==1,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
		su `var'`k' if e(sample)
		estadd scalar mean = r(mean)
		eststo `var'
}
esttab rnpr rnpr_er rnpr_noer rnpr_in rnpr_out using "$results/table5.tex",  booktabs legend replace ///
		keep(stdva)  label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) ///
		mtitles("Any Hospitalization" "Acute" "Non-Acute" "Inpatient" "Outpatient")
esttab npr npr_er npr_noer npr_in npr_out using "$results/table5.tex", booktabs legend append ///
		keep(stdva)  label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 

esttab rnpr_cancer rnpr_cancer_c npr_rest using "$results/lr_hosp_cond`k'.tex",   ///
		booktabs legend replace keep(stdva) ///
		label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) ///
		mtitles("Cancer ICD10" "Cancer ICD10 C" "Other")
esttab npr_cancer npr_cancer_c npr_rest using "$results/lr_hosp_cond`k'.tex", ///
		booktabs legend append keep(stdva) ///
		label b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 
}


* Table7
ge hoursb5 = hours5
replace hours5 = 0 if hours5 ==. & lab_income5!=.

for var wskfrie_overf5 wskpl_overf5 folketrygd5 aap5: ge dX = X >0 if mortality_5year!=1 & year5 != 2020

ge rest_tr5 = dwoverfor5==1 & dfolketrygd5==0 & di5==0 &  dtjenestepensjon_afp5==0 &  unempben5==0 &  dsykepenger5==0 if dtjenestepensjon_afp5!=.

foreach var in work5 lab_income5 dself_inc5 sl_days5 hours5 dwoverfor5 dfolketrygd5 di5 dtjenestepensjon_afp5 unempben5 dsykepenger5 rest_tr5 {
	eststo `var': areg `var' stdva $controls if str_exog_age>=55 & mortality_4year!=1,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'

	eststo `var'55_65: areg `var'  stdva $controls if str_exog_age>=55 & str_exog_age<65 & mortality_4year!=1,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'55_65
	
	eststo `var'65: areg `var'  stdva $controls if str_exog_age>=65 & mortality_4year!=1,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'65
	
	
	
}
esttab work5 lab_income5 dself_inc5 sl_days5 hours5 dwoverfor5 using "$results/lr_y.tex",  replace keep(stdva) ///
	b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) ///
	posthead("\midrule" "\multicolumn{4}{l}{Panel A: 55 or older} \\") mtitles("Work" "Labor Inc" "Any self empl income" "SL Days" "Hours" "Any Transfers")

local group "65"
esttab work5`group' lab_income5`group' dself_inc5`group' sl_days5`group' hours5`group' dwoverfor5`group' using "$results/lr_y.tex",  append keep(stdva) ///
	b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 
	
local group "55_65"
esttab work5`group' lab_income5`group' dself_inc5`group' sl_days5`group' hours5`group' dwoverfor5`group' using "$results/lr_y.tex",  append keep(stdva) ///
	b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 


* Table A17: source of change in transfers
local group "55_65"
esttab dwoverfor5`group' dfolketrygd5`group' di5`group' dtjenestepensjon_afp5`group' unempben5`group' dsykepenger5`group' rest_tr5`group' ///
	using "$results/lr_transfers.tex",  replace keep(stdva) ///
	b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) ///
	mtitles("Any Transfers" "NI Pensions" "DI" "AFP Pensions" "UI" "Sick Leave Income" "Any other")
eststo clear


* Table A18: bounds
su lab_income5 if mortality_4year!=1, d
ge p25 = r(p25)
ge p50 = r(p50)
ge p75 = r(p75)
for num 25 50 75: ge lab_income5_X = lab_income5 if mortality_4year!=1
for num 25 50 75: replace lab_income5_X = pX if mortality_4year==1
drop p25 p50 p75

su sl_days5 if mortality_4year!=1 & (lab_income5>0&lab_income5!=.), d
ge p25 = r(p25)
ge p50 = r(p50)
ge p75 = r(p75)
for num 25 50 75: ge sl_days5_X = sl_days5 if mortality_4year!=1
for num 25 50 75: replace sl_days5_X = pX if mortality_4year==1


foreach var in lab_income5_25 lab_income5_50 lab_income5_75 sl_days5_25 sl_days5_50 sl_days5_75  {
	eststo `var': areg `var' stdva $controls,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'
}
esttab lab_income5_25  lab_income5_50 lab_income5_75 using "$results/lr_bounds.tex",  replace keep(stdva) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 
esttab  sl_days5_25 sl_days5_50 sl_days5_75 using "$results/lr_bounds.tex",  append keep(stdva) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 


for var dsl5 long_leave5 dwoverfor5: ge X_bl = X if mortality_4year!=1
for var dsl5 long_leave5 dwoverfor5: replace X_bl = 0 if mortality_4year==1
for var dsl5 long_leave5 dwoverfor5: ge X_bu = X if mortality_4year!=1
for var dsl5 long_leave5 dwoverfor5: replace X_bu = 1 if mortality_4year==1

foreach var in dwoverfor5_bl dwoverfor5_bu  {
	eststo `var': areg `var' stdva $controls,  a(str_exogGPIDprev) cl(str_exogGPIDnew) 
	su `var' if e(sample)
	estadd scalar mean = r(mean)
	eststo `var'
}
esttab dwoverfor5_bu dwoverfor5_bl using "$results/lr_bounds.tex", append keep(stdva) b(3) se(3) star(* 0.1 ** 0.05 *** 0.01) stats(emp mean N, fmt(%9.3g)) 


